package org.smart4j.framework.Helper;

import java.lang.reflect.Field;
import java.util.Map;

import org.smart4j.framework.Annotation.Inject;
import org.smart4j.framework.Util.ArrayUtil;
import org.smart4j.framework.Util.CollectionUtil;
import org.smart4j.framework.Util.ReflectionUtil;

/**
 * 依赖注入工具类
 */
public final class IocHelper {
    static{
        //获取所有的bean类与bean实例之间的关系，即bean map
        Map<Class<?>, Object> beanMap = BeanHelper.getBeanMap();
        if (CollectionUtil.isNotEmpty(beanMap)){
            for (Map.Entry<Class<?>, Object> beanEntry : beanMap.entrySet()){
                Class<?> beanClass = beanEntry.getKey();
                Object beanInstance = beanEntry.getValue();

                //获取所有成员变量
                Field[] beanFields = beanClass.getDeclaredFields();
                if (ArrayUtil.isNotEmpty(beanFields)){
                    for (Field beanField : beanFields){
                        if (beanField.isAnnotationPresent(Inject.class)){
                            //成员变量需要自动注入
                            Class<?> beanFieldClass = beanField.getType();
                            Object beanFieldInstance = beanMap.get(beanFieldClass);

                            if (beanFieldInstance != null){
                                //通过反射初始化beanField的值
                                ReflectionUtil.setField(beanInstance,beanField,beanFieldInstance);
                            }
                        }
                    }
                }

            }
        }
    }
}
